package com.bigdatan.b2c.service.glass.impl;

import com.alibaba.fastjson.JSON;
import com.bigdatan.b2c.controller.glass.enums.DotCountTypeEnum;
import com.bigdatan.b2c.entity.glass.Count;
import com.bigdatan.b2c.mapper.IBaseDao;
import com.bigdatan.b2c.mapper.glass.CountMapper;
import com.bigdatan.b2c.service.glass.ICountService;
import com.bigdatan.b2c.service.impl.BaseServiceImpl;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by shangdong on 17/5/14.
 */
@Slf4j
@Service
public class CountServiceImpl extends BaseServiceImpl<Count> implements ICountService {

    @Resource
    private CountMapper countMapper;

    private static final ConcurrentMap<Integer,AtomicInteger> countCache = Maps.newConcurrentMap();

    private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);

    @PostConstruct
    public void init(){
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            for (Integer integer : countCache.keySet()) {
                Count count = new Count();
                count.setId(integer);
                count.setType(integer);
                count.setCount(countCache.get(integer).get());
                count.setState(1);
                Date time = new Date();
//                count.setCreateTime(createTime);
                count.setUpdateTime(time);
                addDotCount(count);
            }
        },0,30, TimeUnit.MINUTES);
    }
    @Override
    protected IBaseDao<Count> getMapper() {
        return countMapper;
    }

    public boolean addDotCount(DotCountTypeEnum typeEnum){
        AtomicInteger atomicInteger = countCache.get(typeEnum.getTypeID());
        if (atomicInteger == null){
            countCache.put(typeEnum.getTypeID(),new AtomicInteger(1));
            return true;
        }
        atomicInteger.incrementAndGet();
        return true;
    }

    public boolean addDotCount(Count count){
        try {
            if (count.getId() > 0){//update
                int i = countMapper.updateByPrimaryKeySelective(count);
                if (i > 0){
                    return true;
                }
            }else {//insert
                int i = countMapper.insertSelective(count);
                if (i > 0){
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            log.error("addDotCount error! req = "+ JSON.toJSONString(count),e);
            return false;
        }
    }



}
